package com.github.defense.plugin.gray.instance;


import com.github.defense.plugin.gray.constants.GrayClientConstant;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 区分灰度实例和正常实例
 * @Author: lettger
 * @Date: 2021/6/18 1:20 下午
 */
public interface GrayInstanceSorter {
    /**
     * 实例筛选归类
     * @param instances
     * @return
     */
    GrayInstanceList sorter(List<GrayInstance> instances);

    /**
     * 灰度决策过滤满足条件的实例
     * @param instances
     * @return
     */
    List<GrayInstance> filterDecisions(List<GrayInstance> instances);

    /**
     * 过滤灰度实例
     * @param instances
     * @return
     */
    default List<GrayInstance> filterGrayInstance(List<GrayInstance> instances){
        return instances.stream().filter(
                instance -> {
                    Map<String, Object> metaData = instance.getMetadata();
                    return Objects.nonNull(metaData)
                            && metaData.containsKey(GrayClientConstant.GRAY_INSTANCE_ENABLE)
                            && Boolean.parseBoolean(metaData.get(GrayClientConstant.GRAY_INSTANCE_ENABLE).toString());
                }
        ).collect(Collectors.toList());
    }

    /**
     * 过滤正常实例
     * @param instances
     * @return
     */
    default List<GrayInstance> filterNormalInstance(List<GrayInstance> instances){
        return instances.stream().filter(
                instance -> {
                    Map<String, Object> metaData = instance.getMetadata();
                    return Objects.isNull(metaData)
                            || !metaData.containsKey(GrayClientConstant.GRAY_INSTANCE_ENABLE)
                            || !Boolean.parseBoolean(metaData.get(GrayClientConstant.GRAY_INSTANCE_ENABLE).toString());
                }
        ).collect(Collectors.toList());
    }
}
